package com.langsin.Search;

import java.util.Arrays;

/**
 * @Auther: MFM
 * @Date: 2021/8/19 - 08 - 19 - 17:01
 * @version: 1.0
 */

public class FibonacciSearch {

    public static int maxSize = 20;


    /**
     * @return 斐波那契数列
     */
    public static int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < maxSize; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f;
    }

    /**
     * 斐波那契查找
     *
     * @param arr 待查找数组
     * @param key 待查找数值
     * @return 下标
     */
    public static int fibSearch(int[] arr, int key) {
        int low = 0;
        int high = arr.length - 1;
        int k = 0;//斐波那契下标
        int mid = 0;//存放mid值
        int[] f = fib();
        while (high > f[k] - 1) {
            k++;
        }
        int[] temp = Arrays.copyOf(arr, f[k]);
        for (int i = high + 1; i < arr.length; i++) {
            temp[i] = arr[high];
        }

        while (low <= high) {
            mid = low + f[k - 1] - 1;//核心！
            if (key < temp[mid]) {//小于则往左走
                high = mid - 1;
                //f[k] = f[k-1] + f[k-2]
                k--;
            } else if (key > temp[mid]) {//大于则往右走
                low = mid + 1;
                k-=2;
            }else {
                if (mid<=high){
                    return mid;
                }else {
                    return high;
                }
            }
        }

        return -1;
    }
}
